package com.example.admin.controller.InterviewRecord;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.airobotinterviewrecord.entity.InterviewRecord;
import com.example.airobotinterviewrecord.service.IInterviewRecordService;
import com.example.airobotinterviewrecord.util.Result;
import com.example.airobotpositions.dao.PositionQueryDto;
import com.example.airobotpositions.service.IInterviewPositionsService;
import com.example.candiates.domain.InterviewCandidates;
import com.example.candiates.service.InterviewCandidatesService;
import com.example.interviewer.domain.DigitalInterviewers;
import com.example.interviewer.service.IDigitalInterviewersService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 面试记录表 前端控制器
 * </p>
 *
 * @author author
 * @since 2025-04-07
 */
@RestController
@RequestMapping("/interview-record")
public class InterviewRecordController {
    private static final Logger logger = LoggerFactory.getLogger(InterviewRecordController.class);

    @Autowired
    private IInterviewRecordService recordService;

    @Autowired
    private InterviewCandidatesService candidatesService;
    
    @Autowired
    private IInterviewPositionsService positionsService;
    
    @Autowired
    private IDigitalInterviewersService interviewersService;

    //    面试记录表全查
    @GetMapping("/getAllRecord")
    public ResponseEntity<Result> getAllRecords(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {
        try {
            logger.info("开始获取面试记录列表, 页码: {}, 每页数量: {}", pageNum, pageSize);
            IPage<InterviewRecord> page = recordService.listRecordsByPage(pageNum, pageSize);
            return ResponseEntity.ok(Result.pageSuccess(page));
        } catch (Exception e) {
            logger.error("获取面试记录列表失败: ", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error("获取列表失败: " + e.getMessage()));
        }
    }

    // 新增
    @PostMapping("/addRecord")
    public ResponseEntity<Result> add(@Valid @RequestBody InterviewRecord record) {
        try {
            logger.info("开始添加面试记录: {}", record);
            
            // 设置创建时间和更新时间
            LocalDateTime now = LocalDateTime.now();
            record.setCreatedAt(now);
            record.setUpdatedAt(now);
            
            String result = recordService.addRecord(record);
            logger.info("面试记录添加成功: {}", result);
            return ResponseEntity.ok(Result.success(result));
        } catch (IllegalArgumentException e) {
            logger.error("添加面试记录参数错误: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(Result.error(e.getMessage()));
        } catch (Exception e) {
            logger.error("添加面试记录失败: ", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error("添加失败: " + e.getMessage()));
        }
    }

    // 删除
    @DeleteMapping("/deleteRecord/{id}")
    public ResponseEntity<Result> delete(@PathVariable Integer id) {
        try {
            logger.info("开始删除面试记录, ID: {}", id);
            String result = recordService.deleteRecordById(id);
            logger.info("面试记录删除成功: {}", result);
            return ResponseEntity.ok(Result.success(result));
        } catch (IllegalArgumentException e) {
            logger.error("删除面试记录参数错误: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(Result.error(e.getMessage()));
        } catch (Exception e) {
            logger.error("删除面试记录失败: ", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error("删除失败: " + e.getMessage()));
        }
    }

    // 更新
    @PostMapping("/updateRecord")
    public ResponseEntity<Result> updateRecord(@Valid @RequestBody InterviewRecord record) {
        try {
            logger.info("开始更新面试记录: {}", record);
            
            // 设置更新时间
            record.setUpdatedAt(LocalDateTime.now());
            
            String result = recordService.updateRecord(record);
            logger.info("面试记录更新成功: {}", result);
            return ResponseEntity.ok(Result.success(result));
        } catch (IllegalArgumentException e) {
            logger.error("更新面试记录参数错误: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(Result.error(e.getMessage()));
        } catch (Exception e) {
            logger.error("更新面试记录失败: ", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error("更新失败: " + e.getMessage()));
        }
    }

    // 获取候选人列表
    @GetMapping("/candidate/list")
    public ResponseEntity<Result> getCandidateList() {
        try {
            logger.info("开始获取候选人列表");
            List<InterviewCandidates> candidates = candidatesService.list();
            return ResponseEntity.ok(Result.success(candidates));
        } catch (Exception e) {
            logger.error("获取候选人列表失败: ", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error("获取候选人列表失败: " + e.getMessage()));
        }
    }

    // 获取职位列表
    @GetMapping("/position/list")
    public ResponseEntity<Result> getPositionList() {
        try {
            logger.info("开始获取职位列表");
            PositionQueryDto queryDto = new PositionQueryDto();
            queryDto.setIsPaged(false); // 设置为不分页查询
            Object result = positionsService.queryPositions(queryDto);
            logger.info("获取职位列表成功，结果: {}", result);
            return ResponseEntity.ok(Result.success(result));
        } catch (Exception e) {
            logger.error("获取职位列表失败: ", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error("获取职位列表失败: " + e.getMessage()));
        }
    }

    // 获取面试官列表
    @GetMapping("/interviewer/list")
    public ResponseEntity<Result> getInterviewerList() {
        try {
            logger.info("开始获取面试官列表");
            Page<DigitalInterviewers> page = interviewersService.selectDigitalInterviewersList(new DigitalInterviewers(), 1, Integer.MAX_VALUE);
            return ResponseEntity.ok(Result.success(page.getRecords()));
        } catch (Exception e) {
            logger.error("获取面试官列表失败: ", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error("获取面试官列表失败: " + e.getMessage()));
        }
    }

    // 根据ID获取面试记录详情
    @GetMapping("/getRecordById/{id}")
    public ResponseEntity<Result> getRecordById(@PathVariable Integer id) {
        try {
            InterviewRecord record = recordService.getById(id);
            if (record != null) {
                return ResponseEntity.ok(Result.success(record));
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(Result.error("未找到该面试记录"));
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error("查询失败: " + e.getMessage()));
        }
    }

    // 根据数字人面试官ID查询面试记录
    @GetMapping("/getRecordsByDigitalInterviewerId/{digitalInterviewerId}")
    public ResponseEntity<Result> getRecordsByDigitalInterviewerId(@PathVariable Integer digitalInterviewerId) {
        try {
            List<InterviewRecord> records = recordService.getRecordsByDigitalInterviewerId(digitalInterviewerId);
            return ResponseEntity.ok(Result.success(records));
        } catch (Exception e) {
            logger.error("根据数字人面试官ID查询面试记录失败: ", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error("查询失败: " + e.getMessage()));
        }
    }
}